
//  LifeViewController.m
//  LazyCat
//
//  Created by zhanshu on 15/9/7.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//
#import "LifeViewController.h"
#import "MessageCell2.h"
#import "AFNetworkHandler.h"
#import "MessShowView.h"
#import "LoginViewController.h"
#import "MJChiBaoZiHeader.h"
#import "Html5ViewController.h"
#import "FeWifiManHub.h"
@interface LifeViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@end

@implementation LifeViewController
{
    UITableView *_tableView;
    UIView *_lineView;
    UIView *_bgView;
    NSMutableArray *_dataArray;
    BOOL _isLoading;
    NSString *_urlIndex;
    NSString *_totalCount;
    UIView *_backTView;
    FeWifiManHub *_loading;
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    if ([AppData share].isLoad == YES) {
//        _dataArray = [[NSMutableArray alloc]init];
//        [self getData];
//    }
//    [AppData share].isLoad = NO;
//    _isLoading = NO;
    //下拉刷新
    //[self getData];
    if (kNetworkNotReachability) {
        [[MessShowView share]showWithMess:@"网络不给力"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    _tableView.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(addRefresh)];
    [self getData];
//    [self addRefresh];
    
}
- (void)createUI {
    self.view.backgroundColor = BackColor;
    [self initNav:@"消息中心" doBack:NO];
    UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, 1)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    lineV.alpha = 0.2;
    [self.view addSubview:lineV];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, ScreenHeight-34) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    MJRefreshAutoFooter *foot = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    _tableView.footer = foot;
    _isLoading = NO;
    _urlIndex = @"1";
    _backTView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    _backTView.backgroundColor = BackColor;
    _backTView.hidden = YES;
    [_tableView addSubview:_backTView];
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 80)/2, 100, 80, 90)];
    backImage.image = [UIImage imageNamed:@"noMessage"];
    [_backTView addSubview:backImage];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 200)/2, backImage.frame.origin.y + 90, 200, 50)];
    label.textColor = SetColor(153, 153, 153, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"暂无相关消息";
    [_backTView addSubview:label];
    _dataArray = [[NSMutableArray alloc]init];
    _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 64, _loading.frame.size.width, _loading.frame.size.height);
    [_tableView addSubview:_loading];
    [_loading show];
}
- (void)loadMore {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    if ([_urlIndex integerValue] > [_totalCount integerValue]) {
        [[MessShowView share]showWithMess:@"没有更多数据"];
        return ;
    }
    _urlIndex = [NSString stringWithFormat:@"%ld",[_urlIndex integerValue]+1];
    [self getData];
}
-(void)getData {
    NSString *url = [NSString stringWithFormat:messageUrl,@"66",[AppData share].username,_urlIndex,@"20",@""];
    if ([_urlIndex isEqualToString:@"1"]) {
        [_dataArray removeAllObjects];
    }
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *allDic = result;
        _totalCount = [NSString stringWithFormat:@"%@",[allDic objectForKey:@"totalpage"]];
        NSLog(@"%@",allDic);
        if ([allDic[@"r"] isEqualToString:@"T"]) {
            NSArray *arr = [allDic objectForKey:@"notices"];
            [_dataArray addObjectsFromArray:arr];
            NSString *noreadsystemnoticecount = [NSString stringWithFormat:@"%@",allDic[@"noreadsystemnoticecount"]]; // 未读的系统消息
             NSString *noreadthemenoticecount = [NSString stringWithFormat:@"%@",allDic[@"noreadthemenoticecount"]]; // 未读的主题消息
            if ([noreadthemenoticecount isEqualToString:@"0"] && [noreadsystemnoticecount isEqualToString:@"0"]) {
                [AppData share].baseTabVC.redLable.hidden = YES;
            }else{
                [AppData share].baseTabVC.redLable.hidden = NO;
            }
        }
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        [_loading dismiss];
        [_loading removeFromSuperview];
        if ([_totalCount isEqualToString:@"0"]||_totalCount == nil||[_totalCount isEqualToString:@""]) {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        
        [_tableView reloadData];
        _isLoading = NO;
    }];
    [_tableView.header endRefreshing];
    if (kNetworkNotReachability) {
        _backTView.hidden = NO;
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        [_loading dismiss];
        [_loading removeFromSuperview];
    }else {
        _backTView.hidden = YES;
    }
}
- (void)addRefresh {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
//    MJChiBaoZiHeader *header = [MJChiBaoZiHeader headerWithRefreshingBlock:^{
        _urlIndex = @"1";
//        [header beginRefreshing];
        [self getData];
//    }];
//    _tableView.header = header;
//    header.lastUpdatedTimeLabel.hidden = YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"messagecell2"];
    if (cell == nil) {
        cell = [[MessageCell2 alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"messagecell2"];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSString *str;
    if (indexPath.row < [_dataArray count]) {
    if ([[_dataArray[indexPath.row] objectForKey:@"noticetype"]isEqualToString:@"0"]) {
        str = [NSString stringWithFormat:@"[系统]%@",[_dataArray[indexPath.row] objectForKey:@"title"]];
    }else {
        str = [NSString stringWithFormat:@"[主题]%@",[_dataArray[indexPath.row] objectForKey:@"title"]];
    }
        CGSize size = [str sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:cell.titleLabel.font,NSFontAttributeName, nil]];
        
        
        if (size.width > ScreenWidth - 135) {
            cell.titleLabel.frame = CGRectMake(10, 0, ScreenWidth - 135, 50);
            cell.statusBrn.frame = CGRectMake(10+ScreenWidth - 135, 18, 26, 14);
        }else {
            cell.titleLabel.frame = CGRectMake(10, 0, size.width, 50);
            cell.statusBrn.frame = CGRectMake(20+size.width, 18, 26, 14);
        }
        
        cell.titleLabel.text = str;
        NSString *time = [_dataArray[indexPath.row] objectForKey:@"senddate"];
    time = [time componentsSeparatedByString:@" "][0];
    
    if ([[_dataArray[indexPath.row] objectForKey:@"userread"] isEqualToString:@"0"]) {
        cell.statusBrn.image = [UIImage imageNamed:@"message0"];
    }else {
        cell.statusBrn.image = [UIImage imageNamed:nil];
    }
    cell.timeLabel.text = time;
    }
    cell.titleLabel.font = [UIFont systemFontOfSize:15];
    cell.timeLabel.font = [UIFont systemFontOfSize:15];
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView.tag == 0){
        if (indexPath.row < _dataArray.count) {
            NSDictionary *dict = _dataArray[indexPath.row];
            Html5ViewController *html5VC = [[Html5ViewController alloc]init];
            MessageCell2 *cell = (MessageCell2 *)[_tableView cellForRowAtIndexPath:indexPath];
            cell.statusBrn.hidden = YES;
            NSString *strUrl = [NSString stringWithFormat:detailMessage,[AppData share].username,dict[@"id"],[Utils md5SignStr]];
            html5VC.requestUrl = strUrl;
            if ([[_dataArray[indexPath.row] objectForKey:@"noticetype"]isEqualToString:@"0"]) {
                html5VC.titleStr = @"系统消息";
            }else {
                html5VC.titleStr = @"主题消息";
            }
            //html5VC.relod = @"yes";
            [self.navigationController pushViewController:html5VC animated:YES];
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

@end
